package com.mani.geotag;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.mani.geotag.ContactsDialog.ContactsData;
import com.mani.geotag.ContactsDialog.ContactsItemCallBack;
import com.mani.geotag.FaceBookClient.FaceBookCallBack;


public class CircularActivity extends MapActivity implements FaceBookCallBack,ContactsItemCallBack{
	
	MapView mapview;
	CircularApplication app;
	private MapController myMapController;
	private static int PORTRAIT_ORIENTATION = 1;
	private static int LANDSCAPE_ORIENTATION = 2;
	private int TWITTER_AUTHENTICATE = 3;
	final String FONT_TTF = "bandless.ttf";
	static Typeface mFont;	
	Handler mHandler = new Handler();
	FaceBookClient mFacebookClient;
	FaceBookClient mFacebookPostClient;
	Context mContext;
	TextView mTwitter;
	TextView mFacebook;
	com.mani.geotag.CheckBoxView mTwitterCheckBox;
	com.mani.geotag.CheckBoxView mFacebookCheckBox;
	EditText mOption;
	Button mAddContacts;
	TextView mAdd;
	TextView mShare;
	ContactsDialog mContactsDialog;
	ProgressDialog mProgressDialog;
	String mLocation;
	double mLatitude;
	double mLongitude;
	String mTinyUrl;
	String mDownloadMapurl;
	CustomItemizedOverlay mItemizedoverlay;
	List<Overlay> mapOverlays;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        mContext = this;
        app = (CircularApplication) this.getApplication();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
        registerReceiver(mBroadcastReceiver, filter);
	    Intent intent = getIntent();
	    mLocation = intent.getStringExtra("location");
	    mLatitude = intent.getDoubleExtra("latitude", 0.0f);
	    mLongitude = intent.getDoubleExtra("longitude",0.0f);        
        Animation a = AnimationUtils.loadAnimation(this, R.anim.scaleanimation);
        mTwitter = (TextView) findViewById(R.id.twitter);
        mFacebook = (TextView) findViewById(R.id.facebook);
        mapview = (MapView)findViewById(R.id.mapview);
        mShare = (TextView) findViewById(R.id.share);
        mAdd = (TextView) findViewById(R.id.addcontacts);
        mOption = (EditText) findViewById(R.id.option);
        mTwitter.setText(this.getString(R.string.sign_in));
        mFacebook.setText(this.getString(R.string.sign_in));
        mAdd.setText(this.getString(R.string.pick_contact));
        mShare.setText(this.getString(R.string.share));
        mTwitter.setTypeface(getTypeface(this,FONT_TTF));
        mFacebook.setTypeface(getTypeface(this,FONT_TTF));
        mShare.setTypeface(getTypeface(this,FONT_TTF));
        mAdd.setTypeface(getTypeface(this,FONT_TTF));
        mOption.setTypeface(getTypeface(this,FONT_TTF));
        mTwitterCheckBox = (com.mani.geotag.CheckBoxView) findViewById(R.id.twitterchkbox);
        mFacebookCheckBox = (com.mani.geotag.CheckBoxView) findViewById(R.id.facebookchkbox);
        mFacebookClient  = new FaceBookClient(this,this);
        mapview.setBuiltInZoomControls(true);
		myMapController = mapview.getController();
		myMapController.animateTo(new GeoPoint((int)(mLatitude * 1E6),(int)(mLongitude * 1E6)));
	    myMapController.setZoom(18); //Fixed Zoom Level
	    mapOverlays = mapview.getOverlays();
	    mapOverlays.clear();

	    Drawable drawable = this.getResources().getDrawable(R.drawable.facebook);
	    drawable.setAlpha(0);
	    mItemizedoverlay = new CustomItemizedOverlay(drawable,this);
	    GeoPoint point;
	    OverlayItem overlayitem;

	    point = new GeoPoint((int)(mLatitude * 1E6),(int)(mLongitude * 1E6));
    	String infoString;
    	infoString = mLocation;
    	overlayitem = new OverlayItem(point,"2mins",infoString);
    	mItemizedoverlay.addOverlay(overlayitem);
	    mapOverlays.add(mItemizedoverlay);
		mapview.invalidate();
	
	    mContactsDialog = new ContactsDialog(this,this);
	    mProgressDialog = new ProgressDialog(this);
	    WindowManager.LayoutParams params = getWindow().getAttributes();  

        int mapViewHeight =0 ;
        if(getscreenOrientation() == PORTRAIT_ORIENTATION) {
        	if(mHeight == 320 || mHeight == 240) {
		        params.height = (mHeight*80)/100;  
		        mapViewHeight = ( ((mHeight*80)/100 ) * 50 )/100;
		        params.y = 5;
        	} else {
		        params.height = (mHeight*65)/100;  
		        mapViewHeight = ( ((mHeight*65)/100 ) * 50 )/100;
		        params.y = 50;
        	}
        } else {
	        params.height = (mHeight*90)/100;
	        params.width = (mWidth*80)/100;
	        mapViewHeight = ( ((mHeight*90)/100 ) * 50 )/100;
	        if(mHeight == 320 || mHeight == 240) {
	        	params.y = 5;
	        } else {
		        params.y = 50;
		        params.x = 50;
	        }
        }
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, mapViewHeight);
        mapview.setLayoutParams(params1);

        this.getWindow().setAttributes(params);	    
	    
        mTwitter.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
		    	AuthenticateTwitter();
			}
		});
        
        mFacebook.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {       
				if(checkInternetConnection() == true) {
					FaceBookClient client = new FaceBookClient(CircularActivity.this,CircularActivity.this);
					client.initialize();
				} else {
					   LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);							 
					   View layout = inflater. inflate(R.layout.custom_toast, null);
					   TextView message = (TextView)layout.findViewById(R.id.message);
					   message.setText(CircularActivity.this.getString(R.string.enable_internet));
					   Toast toastView = new Toast(mContext);
					   toastView.setView(layout);
					   toastView.setDuration(Toast.LENGTH_SHORT);
					   toastView.setGravity(Gravity.CENTER, 0,0);
					   toastView.show();
				}
			}
			});
        
        mAdd.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doLaunchContactPicker();
			}
		});
        mShare.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				boolean sms = false,twitter = false,facebook = false;
				if(mSelectedList != null)
					sms = true;
				if(mTwitterCheckBox.isChecked() == true)
					twitter = true;
				if(mFacebookCheckBox.isChecked() == true)
					facebook = true;
				if(sms == false && twitter == false && facebook == false ) {
					return;
				}
				
				if(sms == false && checkInternetConnection() == false) {
					new ErrorDialog(mContext,CircularActivity.this.getString(R.string.enable_internet)).show();
					return;
				} 
				if(sms == true && twitter == false && facebook == false) {
					mProgressDialog.setStates(twitter, facebook, sms);
					mProgressDialog.show();
					
					if(mSelectedList != null)
						sendTextMessage();
					mSelectedList = null;
					mAdd.setText(CircularActivity.this.getString(R.string.pick_contact));
					return;
				}
				if( twitter || facebook || sms ) {
					mProgressDialog.setStates(twitter, facebook, sms);
					mProgressDialog.show();
					mTinyUrl = getTinyUrl();
					mDownloadMapurl="http://maps.googleapis.com/maps/api/staticmap?center="+mLatitude+","+mLongitude+"&markers=color:blue|label:S|"+mLatitude+","+mLongitude+"&zoom=17&size=800x800&scale=2&sensor=false";
					if(mSelectedList != null)
						sendTextMessage();
					if(mTwitterCheckBox.isChecked() == true)
						sendTweet("@"+mLocation+"--"+mTinyUrl);
					if(mFacebookCheckBox.isChecked() == true) {
				        mFacebookClient.setAccessToken(app.getFacebookToken());  
						mFacebookClient.PostWallMessage("@"+mLocation+"--"+mOption.getText().toString(),mTinyUrl,mDownloadMapurl);
					}
					mSelectedList = null;
					mAdd.setText(CircularActivity.this.getString(R.string.pick_contact));
					mFacebookCheckBox.isCheckDrawn = false;
					mFacebookCheckBox.invalidate();
					mTwitterCheckBox.isCheckDrawn = false;
					mTwitterCheckBox.invalidate(); 
				}
			}
		});
        
        if(app.isTwitterAutheticated() == true) {
        	mTwitterCheckBox.setVisibility(View.VISIBLE);
        	mTwitter.setVisibility(View.GONE);
        }
        
        if(app.isFacebookAuthenticated() == true) {
        	mFacebookCheckBox.setVisibility(View.VISIBLE);
        	mFacebook.setVisibility(View.GONE);
        }
        
        mTwitter.startAnimation(a);
        mFacebook.startAnimation(a);
        mAdd.startAnimation(a);
        mShare.startAnimation(a);
        mOption.startAnimation(a);
    }

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    	public void onReceive(Context context, Intent intent) {
		    String action = intent.getAction();
		    if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
		    	((WindowManager)CircularActivity.this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
				mWidth = metrics.widthPixels;
				mHeight = metrics.heightPixels;
		        WindowManager.LayoutParams params = getWindow().getAttributes();  
		        params.x = 0;  
		        int mapViewHeight =0 ;
		        if(getscreenOrientation() == PORTRAIT_ORIENTATION) {
		        	if(mHeight == 320 || mHeight == 240) {
				        params.height = (mHeight*80)/100;  
				        mapViewHeight = ( ((mHeight*80)/100 ) * 50 )/100;
				        params.y = 50;
		        	} else {
				        params.height = (mHeight*65)/100;  
				        mapViewHeight = ( ((mHeight*65)/100 ) * 50 )/100;
				        params.y = 50;
		        	}
		        } else {
			        params.height = (mHeight*90)/100;
			        params.width = (mWidth*80)/100;
			        mapViewHeight = ( ((mHeight*90)/100 ) * 50 )/100;
			        params.y = 50;
			        params.x = 50;
		        }
		        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, mapViewHeight);
		        mapview.setLayoutParams(params1);
		        CircularActivity.this.getWindow().setAttributes(params);	    

		    } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
		    	CircularActivity.this.finish();
		    }
    	}
    };
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	unregisterReceiver(mBroadcastReceiver);
    	if(smsReceiver == true)
    		unregisterReceiver(mSmsSentReceiver);
    	mContactsDialog.stopThread();
    }
    
    public void onResume() {
    	super.onResume();
    	if(app.isTwitterAutheticated() == true) {
        	mTwitterCheckBox.setVisibility(View.VISIBLE);
        	mTwitter.setVisibility(View.GONE);
    	}
    }

    public void onBackPressed() {
    	mContactsDialog.stopThread();
    	this.finish();
    }
    
	public static Typeface getTypeface(Context context, String typeface) {
	    if (mFont == null) {
	        mFont = Typeface.createFromAsset(context.getAssets(), typeface);
	    }
	    return mFont;
	}
	
    int mHeight;
    int mWidth;
	DisplayMetrics metrics = new DisplayMetrics();

	public int getscreenOrientation()
	{
		((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
		mWidth = metrics.widthPixels;
		mHeight = metrics.heightPixels;
		
		if( metrics.heightPixels > 	metrics.widthPixels )
			return PORTRAIT_ORIENTATION;
		else
			return LANDSCAPE_ORIENTATION;
	}
	
	public void moveToCurrentLocation() {
		myMapController = mapview.getController();
		myMapController.animateTo(new GeoPoint((int)(mLatitude * 1E6),(int)(mLongitude * 1E6)));
	    myMapController.setZoom(18); //Fixed Zoom Level
	}
	protected boolean isRouteDisplayed() {
	    return false;
	}

	private boolean checkInternetConnection() {

		ConnectivityManager conMgr = (ConnectivityManager) this.getSystemService (this.CONNECTIVITY_SERVICE);

		if (conMgr.getActiveNetworkInfo() != null
		&& conMgr.getActiveNetworkInfo().isAvailable()
		&& conMgr.getActiveNetworkInfo().isConnected()) {
			return true;
		} else {
			return false;
		}
	}
	
	private static final int CONTACT_PICKER_RESULT = 1001;  
	  
	public void doLaunchContactPicker() {
		mContactsDialog.show();
	}  
	
	ArrayList<ContactsData> mSelectedList;
	public void onContactsSelected(ArrayList<ContactsData> list) {
		mSelectedList = list;
		String tmp = new String();
		for(int i=0;i<list.size();i++) {
			if(list.get(i).mCheckBox != null && list.get(i).mCheckBox.isChecked() == true) {
				tmp += list.get(i).name+",";
			}
		}
		if(tmp.length() != 0)
			mAdd.setText(tmp);
		else
			mAdd.setText(CircularActivity.this.getString(R.string.pick_contact));
		tmp = null;
	}
	
	public void AuthenticateTwitter() {
		if(checkInternetConnection() == true) {
        	if (app.isTwitterAutheticated() == false) {

				Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
				startActivityForResult(i,TWITTER_AUTHENTICATE);
        	}
			}else {
				   LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);							 
				   View layout = inflater. inflate(R.layout.custom_toast, null);
				   TextView message = (TextView)layout.findViewById(R.id.message);
				   message.setText(CircularActivity.this.getString(R.string.enable_internet));
				   Toast toastView = new Toast(mContext);
				   toastView.setView(layout);
				   toastView.setDuration(Toast.LENGTH_SHORT);
				   toastView.setGravity(Gravity.CENTER, 0,0);
				   toastView.show();
			}
	}
	
	 protected void onActivityResult(int requestCode, int resultCode,
             Intent data) {
		 if (requestCode == TWITTER_AUTHENTICATE) {
			 
             if (resultCode == RESULT_OK) {
                	mTwitterCheckBox.setVisibility(View.VISIBLE);
                	mTwitter.setVisibility(View.GONE);
             }
		 }
	 }

	 public void onFaceBookAuthenticateCompleted(int response,String token,String username)
		{
			switch(response)
			{
			case FaceBookCallBack.AUTHENTICAION_SUCCESSFULL:
			    
			    mFacebookClient.setAccessToken(app.getFacebookToken());
				mHandler.postDelayed(new Runnable() {
					public void run() {
			        	mFacebookCheckBox.setVisibility(View.VISIBLE);
			        	mFacebook.setVisibility(View.GONE);				
					}
				}, 200);
				break;
			case FaceBookCallBack.AUTHENTICAION_FAILURE:
				break;
			}
		}	
		public void onFaceBookmessagePostCompleted(int response)
		{
			switch(response)
			{
			case FaceBookCallBack.POST_SUCCESSFULL:
				 mHandler.post(new Runnable() {
					 public void run() {
						   mProgressDialog.updateFaceBookSuccess();					   
					 }
				 });
			}
		}
				
	 public void sendTweet(String msg) {
			final String msgg = msg;
			Thread t = new Thread() {
		        public void run() {
		        	
		        	try {
		        		TwitterUtils.sendTweet(app,msgg);
		        		mHandler.post(new Runnable() {
							public void run() {
							   mProgressDialog.updateTwitterSuccess();
							}
						 });

					} catch (Exception ex) {
						ex.printStackTrace();
					}
		        }
		    };
		    t.start();
		}
	 
	 int smsCount = 0;
	 boolean smsReceiver = false;
	private BroadcastReceiver mSmsSentReceiver = new BroadcastReceiver() {
        public void onReceive(Context arg0, Intent arg1) {
		        switch (getResultCode())
		        {
		            case Activity.RESULT_OK:
		            	if(smsCount == mSelectedList.size() )
		            	{
		 				   	mProgressDialog.updateSmsSent();
		            		smsCount = 0;
		            		mSelectedList = null;
		            		unregisterReceiver(mSmsSentReceiver);
		            	} else
		            		smsCount++;
		            	
		                break;
		            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
		            	mProgressDialog.updateSmsFailure(mContext.getString(R.string.sms_general_failure));
		                break;
		            case SmsManager.RESULT_ERROR_NO_SERVICE:
		            	mProgressDialog.updateSmsFailure(mContext.getString(R.string.nosms_service));
		                break;
		            case SmsManager.RESULT_ERROR_NULL_PDU:
		            	mProgressDialog.updateSmsFailure(mContext.getString(R.string.sms_general_failure));
		                break;
		            case SmsManager.RESULT_ERROR_RADIO_OFF:
		            	mProgressDialog.updateSmsFailure(mContext.getString(R.string.sms_general_failure));
		                break;
		        } // End of Switch
        	} // End of onReceive()

	};
	
	 public void sendTextMessage() {
		String SENT = "SMS_SENT";
        SmsManager sms = SmsManager.getDefault();
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);
        smsReceiver = true;
        //---when the SMS has been sent---
        registerReceiver(mSmsSentReceiver, new IntentFilter(SENT));
            
		for(int i=0;i<mSelectedList.size();i++) {
			sms.sendTextMessage(mSelectedList.get(i).phone,null,"@ "+mLocation+"--"+mOption.getText().toString()+"--"+this.mTinyUrl
					,sentPI,null);
		}
	}
	
	String tinyURLApi="https://api-ssl.bitly.com/v3/shorten?login=smanikandan14&apiKey=R_eb505b09c9500b0eee90be868dd6895f&format=json&longUrl=";
	public String getTinyUrl() {
		String tinyurl = null;
	  	HttpClient client = new DefaultHttpClient();
		try {
			String query = URLEncoder.encode("http://maps.googleapis.com/maps/api/staticmap?center="+mLatitude+","+mLongitude+"&markers=color:blue|label:S|"+mLatitude+","+mLongitude+"&zoom=17&size=400x400&sensor=true", "utf-8");
			String url = tinyURLApi+query;
			URI uri = new URI(url);
			HttpGet request = new HttpGet(uri);
			
			// Set the timeout in milliseconds until a connection is established.
			int timeoutConnection = 5000;
			HttpConnectionParams.setConnectionTimeout(client.getParams(), timeoutConnection);
			// Set the default socket timeout (SO_TIMEOUT) 
			// in milliseconds which is the timeout for waiting for data.
			int timeoutSocket = 5000;
			HttpConnectionParams.setSoTimeout(client.getParams(), timeoutSocket);
			
			HttpResponse response = client.execute(request);
			
	        InputStream in = response.getEntity().getContent();
	        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	        StringBuilder str = new StringBuilder();
	        String line = null;
	        while((line = reader.readLine()) != null){
	            str.append(line + "\n");
	        }
	        in.close();
	        tinyurl = str.toString();
			//Parse the result.
	         JSONObject json=new JSONObject(tinyurl);
	         json = json.getJSONObject("data");
	         if(json.has("url") == true ) {
	        	 tinyurl=json.get("url").toString();
	         }
		}catch (URISyntaxException e){
			tinyurl = null;
		}
		catch(Exception ex){
			tinyurl = null;
		}
		
		return tinyurl;
	}
}